package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-07-21
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final UserMapper userMapper;
    private final RestTemplate restTemplate;
    private final WeChatProperties weChatProperties;
    private final JwtProperties jwtProperties;
    private final static String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public UserLoginVO wxlogin(UserLoginDTO userLoginDTO) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        // 构建请求URL
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(WX_LOGIN);
        map.forEach((key, value) -> builder.queryParam(key, value));
        String finalUrl = builder.build().encode().toUriString();
        System.out.println("Final URL: " + finalUrl);
        ResponseEntity<String> response = restTemplate.getForEntity(finalUrl, String.class);
        //从返回的json中获取openid
        JSONObject jsonObject = JSON.parseObject(response.getBody());
        String openid = jsonObject.getString("openid");
        if(StrUtil.isBlank(openid)){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        QueryWrapper<User> wrapper=new QueryWrapper<User>()
                .eq("openid",openid);
        User user = userMapper.selectOne(wrapper);
        //如果根据openid查询不到这个用户，那么就认为是新用户
        //就将这个用户添加到用户表里面
        if(user==null){
            user=User.builder()
                    .openid(openid)
                    .build();
            userMapper.insert(user);
        }

        //生成jwt令牌
        Map<String, Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token= JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
        UserLoginVO userLoginVO =UserLoginVO.builder()
                .openid(openid)
                .token(token)
                .id(user.getId())
                .build();
//        BaseContext.setCurrentId(user.getId());
        return userLoginVO;
    }
}
